package org.tong.pdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author
 * @date 2022-10-09 13:37
 */
@Configuration
public class PdfCfg {

    @Bean
    public FontProvider getFontProvider() throws IOException {
        FontProvider provider = new DefaultFontProvider(true, true, false);
        byte[] bs = null;
        try (InputStream is = PdfCfg.class.getClassLoader().getResourceAsStream("fonts/simsun.ttc")) {
            bs = new byte[is.available()];
            is.read(bs);
        }
        PdfFont pdfFont = PdfFontFactory.createTtcFont(bs, 1, PdfEncodings.IDENTITY_H, false, true);
        provider.addFont(pdfFont.getFontProgram());
        return provider;
    }

    @Bean
    public ConverterProperties converterProperties(FontProvider fontProvider) {
        ConverterProperties cp = new ConverterProperties();
        cp.setFontProvider(fontProvider);
        return cp;
    }
}
